package top.hudk.peakclipping;

import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * 作用：
 *
 * @author hudk
 * @date 2020/12/16 17:00
 *
 */
public class Test {

    /**
     * 模拟请求的线程个数
     */
    private static final int COUNT = 1000;

    /**
     * 时间窗口长度
     */
    private static final int TIME_WINDOW_LENGTH = 1000;
    /**
     * 限流值，单位时间允许的最多请求个数
     */
    private static final int CURRENT_LIMIT = 50;

    /**
     * 请求的平均时间间隔
     */
    private static final int REQUEST_FREQUENCY = TIME_WINDOW_LENGTH / CURRENT_LIMIT;

    /**
     * 请求线程结束计数器
     */
    private static final CountDownLatch latch = new CountDownLatch(COUNT);

    /**
     * 请求结束标志
     */
    private static volatile boolean over = false;

    public static void main(String[] args) {
        //限流器
        CircularLinkedCurrentLimiter currentLimiter = new CircularLinkedCurrentLimiter(CURRENT_LIMIT, TIME_WINDOW_LENGTH);
        //打印限流器状态
        print(currentLimiter);
        //线程池
        ExecutorService es1 = Executors.newFixedThreadPool(CURRENT_LIMIT);
        //模拟多线程请求
        for(int i = 0; i < COUNT; i++){
            es1.submit(() -> {
                sleep((long) (Math.random() * TIME_WINDOW_LENGTH));
                Boolean check = currentLimiter.count();
                latch.countDown();
            });
            sleep((long)(Math.random() * REQUEST_FREQUENCY * 2));
        }

        try {
            latch.await();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }finally {
            es1.shutdown();
            over = true;
        }

    }

    /**
     * 打印状态
     */
    public static void print(CircularLinkedCurrentLimiter currentLimiter){
        new Thread(new Runnable() {
            @Override
            public void run() {
                while (!over){
                    sleep(10);
                    System.out.print(currentLimiter.toString2());
                }
            }
        }).start();
    }

//    /**
//     * 创建新线程
//     * @param currentLimiter
//     * @return
//     */
//    public static Thread newTread(CircularLinkedCurrentLimiter currentLimiter){
//        return new Thread(() -> {
//            sleep((long) (Math.random() * 1000));
//            Boolean check = currentLimiter.count();
//            latch.countDown();
//        });
//    }

    /**
     * 线程睡眠等待
     * @param time
     */
    public static void sleep(long time){
        try {
            Thread.sleep(time);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }

//    class SimulationRequest implements Runnable{
//
//        @Override
//        public void run() {
//            sleep((long)(Math.random() * 1000));
//            //Boolean check = currentLimiter.count();
//            latch.countDown();
//        }
//    }
}
